package org.example.execute;

import cn.hutool.core.util.StrUtil;
import org.apache.maven.plugin.logging.Log;
import org.example.dto.ColumnDto;
import org.example.service.GenerateCode;
import org.example.utils.HumpUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class Mapper implements GenerateCode  {

    public void execute(Log log, String entity, Properties properties) {
        String className = HumpUtils.className(StrUtil.format("{}_mapper", entity));
        StringBuffer buffer = new StringBuffer();
        try {
            String path = StrUtil.format("src/main/java/{}/{}.java", properties.getProperty("generator.mapper.path").replaceAll("\\.", "/"), className);
            this.createFile(log, path);
            buffer.append(StrUtil.format("package {};\n\n", properties.getProperty("generator.mapper.path")));
            buffer.append(StrUtil.format("import {}.{};\n", properties.getProperty("generator.entity.path"), HumpUtils.className(StrUtil.format("{}_entity", entity))));
            if (properties.containsKey("generator.mapper.extends")) {
                String[] mapperExtends = properties.getProperty("generator.mapper.extends").split(",");
                Arrays.asList(mapperExtends).stream().map(name-> StrUtil.format("import {};\n",name)).distinct().forEach(buffer::append);
                StringBuilder mapperExtend=new StringBuilder();
                Arrays.asList(mapperExtends).stream().map(name -> name.substring(name.lastIndexOf(".")+1)).forEach(name->mapperExtend.append(StrUtil.format(",{}<{}>",name,HumpUtils.className(StrUtil.format("{}_entity", entity)))));
                buffer.append(StrUtil.format("\npublic interface {} extends {} {\n\n}", className,mapperExtend.substring(1)));
            } else {
                buffer.append(StrUtil.format("public interface {} {\n\n}", className));
            }
            writeContent(log, path, buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void execute(Log log, String entity, List<ColumnDto> columnDtoList, Properties properties) {
        Boolean service = Boolean.parseBoolean(properties.getProperty("generator.mapper"));
        if (service) {
            log.info(entity + "service 生成");
            execute(log, entity, properties);
        }
    }
}
